package cn.lastcrdg.testlrslide;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.RelativeLayout;

/**
 * author：liluo
 * e-mail：lastcrazysun@163.com
 * company：cusc
 * date：2017/12/12 16:51
 * description：可以左右滑动别切可以禁止(失败)
 */

public class LRSlideView extends HorizontalScrollView {

    //右侧删除控件
    private RelativeLayout mRlDelete;
    //左侧选择控件
    private RelativeLayout mRlLeft;

    //右侧删除空间宽度
    private int mDeleteWidth;
    //左侧控件宽度
    private int mLeftWidth;
    //down的坐标
    float dX = 0;
    //move与down 之间的差值
    float mX = 0;
    //是否是第一次进入
    private boolean isFirst = true;
    //是否删除为打开状态
    private boolean isOpen;
    //是否编辑为打开状态
    private boolean isOpenEdit;

    public LRSlideView(Context context) {
        this(context, null);
    }

    public LRSlideView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LRSlideView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed && isFirst) {
            isFirst = false;
            //获取左右侧控件的宽度
            mRlDelete = findViewById(R.id.rl_delete);
            mRlLeft = findViewById(R.id.rl_left);
            mLeftWidth = mRlLeft.getWidth();
            mDeleteWidth = mRlDelete.getWidth();

            //将左侧控件滑到屏幕外
            this.scrollTo(mLeftWidth, 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (isOpenEdit){
            //编辑状态不可滑动
            return true;
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                dX = ev.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                mX = ev.getX() - dX;
                if (mX < 0){
                    //左滑
                    if (!isOpen) {
                        isOpen = true;
                        //删除状态，滑动到最右侧
                        smoothScrollTo(mLeftWidth + mDeleteWidth, 0);
                    }
                }else{
                    //右滑
                    if (isOpen){
                        isOpen = false;
                        //正常状态，滑动至初始位置
                        smoothScrollTo(mLeftWidth, 0);
                    }
                }
                break;
            default:
                break;
        }
        return true;
    }

    public void openEdit(boolean openEdit){
        isOpenEdit = openEdit;
        if (openEdit) {
            scrollTo(0, 0);
        }else {
            scrollTo(mLeftWidth, 0);
        }
    }
}
